﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

namespace mojoPortal.Web.RS.SBM.Controls
{
    public partial class ModalManagePaymentControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }
        protected void ddlPaymentType_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            CheckPaymentTypeSelected();
        }
        private void CheckPaymentTypeSelected()
        {
            String paymenttype = ddlPaymentType.SelectedItem.Text.Trim();
            if (paymenttype.Contains("Check") || paymenttype.Contains("Cash"))
            {
                SetCreditCardEnabledState(false);
                RequiredFieldValidator_txtCCExpireDT.Enabled = false;
            }
            else
            {
                SetCreditCardEnabledState(true);
                RequiredFieldValidator_txtCCExpireDT.Enabled = true;
            }
        }
        private void ClearFields()
        {
            txtPaymentAmount.Text = "";
            txtPaymentDT.Text = "";
            txtPaymentId.Text = "";
            txtPaymentNote.Text = "";
            txtCCExpireDT.Text = "";
            txtCCName.Text = "";
            txtCCNumber.Text = "";
            txtCVV.Text = "";
            ddlPaymentType.ClearSelection();
        }
        private void SetCreditCardEnabledState(bool bstate)
        {
            txtCCExpireDT.Enabled = bstate;
            txtCCName.Enabled = bstate;
            txtCCNumber.Enabled = bstate;
            txtCVV.Enabled = bstate;
            if (!bstate)
            {
                txtCCExpireDT.BackColor = System.Drawing.Color.Gainsboro;
                txtCCName.BackColor = System.Drawing.Color.Gainsboro;
                txtCCNumber.BackColor = System.Drawing.Color.Gainsboro;
                txtCVV.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                txtCCExpireDT.BackColor = System.Drawing.Color.White;
                txtCCName.BackColor = System.Drawing.Color.White;
                txtCCNumber.BackColor = System.Drawing.Color.White;
                txtCVV.BackColor = System.Drawing.Color.White;
            }
        }
        public void SetControlEnabledState(bool bstate = false)
        {
            RSSBMCommonFunctions.SetControlsEnabledState(UpdatePanelPayment.ContentTemplateContainer, bstate);
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            if (hfRedirectURL.Value.Length > 0)
                Response.Redirect(hfRedirectURL.Value);
            else
                mpeModalPayment.Hide();
        }


        protected void btnEditPayment_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                btnEditPayment.Visible = false;
                btnSavePayment.Visible = true;
                btnDeletePayment.Visible = true;
                SetControlEnabledState(true);
                CheckPaymentTypeSelected();
            }
            else
                lblMessage.Text = "You Do Not Have Permission To Perform This Action!";
        }
        protected void btnSavePayment_Click(Object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            int CompanyId = userIdentity.RSCompanyId;

            int InvoiceId = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);
            int LocationId = RSSBMCommonFunctions.GetLocationIDByInvoiceID(CompanyId, InvoiceId);
            int PaymentId = txtPaymentId.Text == "" ? 0 : Convert.ToInt32(txtPaymentId.Text);

            if (CompanyId > 0 && LocationId > 0 && InvoiceId > 0)
            {
                string PaymentDate = txtPaymentDT.Text.Trim();
                string PaymentNote = txtPaymentNote.Text.Trim();
                int PaymentTypeId = Convert.ToInt32(ddlPaymentType.SelectedValue);
                float PaymentAmount = txtPaymentAmount.Text == "" ? 0 : Convert.ToSingle(txtPaymentAmount.Text);
                string CCName = txtCCName.Text.Trim();
                string CCNumber = txtCCNumber.Text.Trim();
                string CCExpireDT = txtCCExpireDT.Text.Trim();
                int CVV = txtCVV.Text == "" ? 0 : Convert.ToInt32(txtCVV.Text);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentId", SqlDbType.Int, 0, ParameterDirection.Input, PaymentId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@InvoiceId", SqlDbType.Int, 0, ParameterDirection.Input, InvoiceId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LocationId", SqlDbType.Int, 0, ParameterDirection.Input, LocationId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);

                if (PaymentDate.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(PaymentDate));
                if (CCExpireDT.Trim().Length > 0)
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@CCExpireDT", SqlDbType.DateTime, 0, ParameterDirection.Input, Convert.ToDateTime(CCExpireDT));

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentNote", SqlDbType.NVarChar, -1, ParameterDirection.Input, PaymentNote);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentAmount", SqlDbType.Money, 0, ParameterDirection.Input, PaymentAmount);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PaymentTypeId", SqlDbType.Int, 0, ParameterDirection.Input, PaymentTypeId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CCName", SqlDbType.NVarChar, 50, ParameterDirection.Input, CCName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CCNumber", SqlDbType.NVarChar, 50, ParameterDirection.Input, CCNumber);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CVV", SqlDbType.Int, 0, ParameterDirection.Input, CVV);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSavePayment");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                lblMessage.Text = "Payment Successfully Saved.";
                lblMessage.ForeColor = System.Drawing.Color.DarkBlue;

                btnEditPayment.Visible = false;
                btnSavePayment.Visible = false;
                btnDeletePayment.Visible = false;
                SetControlEnabledState(false);
                hfRedirectURL.Value = Request.RawUrl;
            }
            else
            {
                lblMessage.Text = "Invalid Parameter!";
                lblMessage.ForeColor = System.Drawing.Color.DarkRed;
                hfRedirectURL.Value = "";
            }
        }

        protected void btnDeletePayment_Click(object sender, EventArgs e)
        {
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSCanDelete)
            {
                int companyid = userIdentity.RSCompanyId;

                int paymentid = txtPaymentId.Text == "" ? 0 : Convert.ToInt32(txtPaymentId.Text);
                int invoiceid = txtInvoiceId.Text == "" ? 0 : Convert.ToInt32(txtInvoiceId.Text);

                if (companyid > 0 && invoiceid > 0 && paymentid > 0)
                {
                    SqlCommand sqlCmd = new SqlCommand();
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@paymentid", SqlDbType.Int, 0, ParameterDirection.Input, paymentid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@invoiceid", SqlDbType.Int, 0, ParameterDirection.Input, invoiceid);
                    SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);
                    SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "DELETE FROM rs_tblPayment WHERE InvoiceId=@InvoiceId AND  PaymentId=@PaymentId AND CompanyId=@companyid");
                    SQLHelper.ExecuteScalarCmd(sqlCmd);
                    int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                    string prevurl = string.Empty;
                    if (Session["PreviousURL"] != null)
                        prevurl = Session["PreviousURL"].ToString();
                    else
                        prevurl = Request.UrlReferrer.ToString();
                    lblMessage.Text = "Payment deleted successfully.";
                    hfRedirectURL.Value = Request.RawUrl;
                }
            }
            else
            {
                lblMessage.Text = "You Do Not Have Permission To Perform This Action.";
                hfRedirectURL.Value = "";
            }

            btnEditPayment.Visible = false;
            btnSavePayment.Visible = false;
            btnDeletePayment.Visible = false;
        }

        public void ShowModal(int companyid, int invoiceid, int paymentid)
        {
            hfRedirectURL.Value = "";
            lblMessage.Text = "Payment";

            if (LoadPaymentData(companyid, invoiceid, paymentid))
            {
                btnEditPayment.Visible = true;
                btnSavePayment.Visible = false;
                btnDeletePayment.Visible = false;
                SetControlEnabledState(false);
                CheckPaymentTypeSelected();
            }
            else
            {
                btnEditPayment.Visible = false;
                btnSavePayment.Visible = true;
                btnDeletePayment.Visible = false;
                SetControlEnabledState(true);
            }
            mpeModalPayment.Show();
        }

        private bool LoadPaymentData(int companyid, int invoiceid, int paymentid)
        {
            bool hasValue = false;
            ClearFields();
            RSSBMDataLookupLoader.LoadTypeDDL(companyid, "PAYMENT_CAT", ddlPaymentType);

            if (companyid > 0 && invoiceid > 0)
            {
                txtInvoiceId.Text = invoiceid.ToString();
                if (paymentid > 0)
                {
                    String strSQL = "SELECT * FROM [rs_tblPayment] WHERE paymentid=@paymentid AND companyid=@companyid";
                    SqlCommand myCommand;
                    SqlParameter param;
                    SqlConnection myConnection;
                    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                    myCommand = new SqlCommand(strSQL, myConnection);
                    SqlDataReader myDataReader;

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@companyid";
                    param.Value = companyid;
                    myCommand.Parameters.Add(param);

                    param = new SqlParameter();
                    param.SqlDbType = SqlDbType.Int;
                    param.ParameterName = "@paymentid";
                    param.Value = paymentid;
                    myCommand.Parameters.Add(param);

                    myConnection.Open();
                    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                    if (myDataReader.HasRows)
                    {
                        myDataReader.Read();
                        txtInvoiceId.Text = myDataReader["InvoiceId"].ToString();
                        txtPaymentId.Text = myDataReader["PaymentId"].ToString();
                        txtPaymentAmount.Text = myDataReader["PaymentAmount"].ToString();
                        if (myDataReader["PaymentDT"] != DBNull.Value)
                        {
                            DateTime paymentdt = Convert.ToDateTime(myDataReader["PaymentDT"]);
                            txtPaymentDT.Text = paymentdt.ToShortDateString();
                        }
                        if (myDataReader["PaymentTypeId"] != DBNull.Value)
                            ddlPaymentType.SelectedValue = myDataReader["PaymentTypeId"].ToString();
                        txtCCName.Text = myDataReader["CCName"].ToString();
                        txtCCNumber.Text = myDataReader["CCNumber"].ToString();
                        if (myDataReader["CCExpireDT"] != DBNull.Value)
                        {
                            DateTime ccexpiredt = Convert.ToDateTime(myDataReader["CCExpireDT"]);
                            txtCCExpireDT.Text = ccexpiredt.ToShortDateString();
                        }
                        txtCVV.Text = myDataReader["CVV"].ToString();
                        txtPaymentNote.Text = myDataReader["PaymentNote"].ToString();

                        hasValue = true;
                    }
                }
            }
            return hasValue;
        }
    }
}